package cn.maxhou.service.impl;

import cn.maxhou.entity.SysUser;
import cn.maxhou.mapper.SysUserMapper;
import cn.maxhou.service.SysUserService;
import cn.maxhou.util.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    private static final Logger LOGGER= LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser login(String account, String password) {
        SysUser lohinUser =sysUserMapper.getByAccount(account);
        //如果账号存在且密码相对,则返回查到的登录用户信息
        if(lohinUser!=null && lohinUser.getPassword().equals(password)){
            return lohinUser;
        }
        return null;
    }

    @Override
    public Page<SysUser> findPage(SysUser entity, Integer pageNo, Integer pageSize) throws Exception {
        Page<SysUser>page=null;
        try{
            page=new Page<SysUser>();
            page.setPageNo(pageSize);
            //查询总数,计算总页数
            Long count = sysUserMapper.count(entity);
            page.setTotalCount(count.intValue());
            page.setPageNo(pageNo);
            //查询分页数据
            List<SysUser> data =sysUserMapper.getPage(entity,page.offset(), page.getPageSize());
            page.setData(data);
        }catch (Exception e){
            LOGGER.error("执行SysUserServiceImpl.findPage(SysUser,integer,integer)方法出现异常.",e);
            throw e;
        }
        return page;
    }

    @Override
    public boolean saveOrUpdate(SysUser entity) throws Exception {
        try{
            if(entity.getId()==null){
                //无主键则新增
                return sysUserMapper.insert(entity)>0;
            }else {
                //有主键则修改
                return sysUserMapper.update(entity)>0;
            }
        }catch (Exception e){
            LOGGER.error("执行SysUserServiceImpl.saveOrUpdate(SysUser)方法出现异常.",e);
            throw e;
        }
    }

    @Override
    public SysUser findById(Long id) throws Exception {
        try{
            return sysUserMapper.getById(id);
        }catch (Exception e){
            LOGGER.error("执行SysUserServiceImpl.findById(Long)方法出现异常.",e);
            throw e;
        }
    }

    @Override
    public int deleteById(Long id) throws Exception {
        try{
            return sysUserMapper.deleteById(id);
        }catch (Exception e){
            LOGGER.error("执行SysUserServiceImpl.deleteById(Long)方法出现异常.",e);
            throw e;
        }
    }

    @Override
    public SysUser findByAccount(String account) throws Exception {
        return sysUserMapper.getByAccount(account);
    }

    @Override
    public int changePassword(SysUser sysUser) {
        return sysUserMapper.changePassword(sysUser);
    }
}
